<template>
  <div class="login-container">
    <el-card shadow="hover">
      <!-- 登录标题 -->
      <div class="login-title"></div>
      <!-- 表单盒子 -->
      <el-form ref="form" :model="userInfo" :rules="rules">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="userInfo.username" placeholder="请输入用户名" prefix-icon="el-icon-s-custom"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="userInfo.password"
            type="password"
            show-password
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
      <!-- 登录下面超链接 -->
      <el-link :underline="false" @click="$router.push('/Reg')">还没有账号，去注册</el-link>
      <!-- <router-link to="/reg">还没有账号，去注册</router-link> -->
    </el-card>
  </div>
</template>
<script>
import { loginAPI } from '@/api/reg.js'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名必填', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名必须是1到10位的数字字母', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码必填', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6~15位非空字符串', trigger: 'blur' }
        ]
      }
    }
  },
  // 3. 通过验证，表单提交，完成登录
  methods: {
    login() {
      this.$refs.form.validate(async valid => {
        if (!valid) return // 表单验证未通过，直接 return
        // 表单验证通过，发送请求，完成登录
        // console.log('通过验证')
        const { data: res } = await loginAPI(this.userInfo)
        if (res.code === 0) {
          this.$message.success(res.message)
          // 存储token（调用mutations中的updateToken方法）
          // this.$store.commit('模块名/方法名', '其他参数')
          this.$store.commit('user/updateToken', res.token)
          // 跳转到后台首页
          this.$router.push('/')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style lang="less">
.login-container {
  height: 100%;
  background: url(../assets/images/login_bg.jpg) no-repeat;
  // 让图片居中沾满整个页面
  background-size: cover;
  .el-card {
    // height: 355px;
    width: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    .login-title {
      background: url(../assets/images/login_title.png) 50% no-repeat;
      height: 60px;
    }

    .el-button {
      width: 100%;
    }
  }
}
</style>
